import json
import logging
import os
import time
import traceback
from datetime import datetime
from django.http import JsonResponse
from django.views import View
from django.db import transaction
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from radius.models import Nas
from tools.Tools import createHandleLog, getCurrentUser, check_text, getSourceLen, getDataPaging, rebootRadius

res = dict()
logger_info = logging.getLogger('info')


class NasView(View):
    res.clear()

    def get(self, request, *args, **kwargs):
        try:
            current = request.GET.get("current")
            pageSize = request.GET.get("pageSize")
            shortname = request.GET.get("shortname")
            dataInfo = Nas.objects.all()
            if check_text(shortname):
                dataInfo = dataInfo.filter(shortname=shortname)
            total = getSourceLen(dataInfo)
            data = getDataPaging(dataInfo, int(pageSize), int(current))
            res['status'] = 200
            res['data'] = data
            res['total'] = total
            res['current'] = current
            res['pageSize'] = pageSize
            res['messages'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}\n\n')
            res['status'] = 400
            res['message'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        try:
            body = json.loads(request.body)
            nasname = body.get('nasname')
            shortname = body.get('shortname')
            nas_type = body.get('nas_type')
            description = body.get('description')
            if not Nas.objects.filter(nasname=nasname).exists():
                createData = Nas.objects.create(nasname=nasname, ports=3799, secret='testing123')
                createData.shortname = shortname
                createData.type = nas_type
                createData.description = description
                createData.save()
                rebootRadius()
                res['status'] = 200
                res['message'] = 'NAS添加成功'
                createHandleLog('新增NAS', str(getCurrentUser(request)), body)
                logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增NAS》权限 新增内容 {body}')
            else:
                res['status'] = 400
                res['message'] = '已存在当前NAS，添加失败'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}\n\n')
            res['status'] = 400
            res['message'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def put(self, request, *args, **kwargs):
        try:
            body = json.loads(request.body)
            NasId = body.get('NasId')
            nasname = body.get('nasname')
            shortname = body.get('shortname')
            nas_type = body.get('nas_type')
            description = body.get('description')
            modifyData = Nas.objects.get(id=NasId)
            modifyData.nasname = nasname
            modifyData.shortname = shortname
            modifyData.type = nas_type
            modifyData.description = description
            modifyData.save()
            res['status'] = 200
            res['message'] = 'NAS修改成功'
            createHandleLog('修改NAS', str(getCurrentUser(request)), body)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改NAS》权限 修改内容 {modifyData.shortname} {body}')
            rebootRadius()
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}\n\n')
            res['status'] = 400
            res['message'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def delete(self, request, *args, **kwargs):
        try:
            NasId = request.GET.get("NasId")
            allData = Nas.objects.all()
            total = getSourceLen(allData)
            if total == 1:
                res['status'] = 400
                res['message'] = '当前Nas设备数量为《1》,删除失败'
                return JsonResponse(res, status=HTTP_200_OK)
            delData = Nas.objects.get(id=NasId)
            delData.delete()
            rebootRadius()
            res['status'] = 200
            res['message'] = 'Nas设备：{} 删除成功'.format(delData.shortname)
            createHandleLog('删除客户', str(getCurrentUser(request)), delData.shortname)
            logger_info.info(
                f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除客户》权限 删除内容 {delData.shortname}')
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}\n\n')
            res['status'] = 400
            res['message'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)
